package com.swxy.club.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 易
 */
public class JWTUtil {

    /**
     * 生成token  header.payload.singature
     */
    private static final String SING = "XIAOSHUANG";

    public static String getToken(Map<String, String> map) {

        Calendar instance = Calendar.getInstance();
        // 默认10分钟过期
        instance.add(Calendar.SECOND,60*10);

        //创建jwt builder
        JWTCreator.Builder builder = JWT.create();

        // payload
        map.forEach(builder::withClaim);
        //指定令牌过期时间
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(SING));
    }

    /**
     * 验证token  合法性
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    /**
     * 解析token中的 payload
     */
    public static Map<String, String> getPayload(String token) {
        DecodedJWT decodedJwt = verify(token);

        Map<String, String> result = new HashMap<>();
        result.put("id", decodedJwt.getClaim("id").asString());
        result.put("name", decodedJwt.getClaim("username").asString());
        result.put("idNumber", decodedJwt.getClaim("number").asString());

        return result;
    }


}
